#!encoding=utf-8
#/usr/bin/env python

import subprocess
import time
import ntplib

from subprocess import call
from time import localtime, strftime
from ntplib import NTPException 

"""
Class       : NTPUpdate
Description : A Class which in mainly used to update ntp
"""
class NTPUpdate(object):
    """
    __arguments: NTP Update plugin arguments which store a dictionary
    """
    __arguments    = None

    """
    __ntpServerList: NTP Server List
    """
    _ntpServerList = list()

    """
    __timeout: timeout in numeric seconds
    """
    __timeout      = 5


    """
    Construtor: initillize NTPUpdate
    """
    def  __init__(self, arguments = None):
        super(NTPUpdate, self).__init__()
        if arguments is not None:
            self.__arguments = arguments
            if self.__arguments.has_key('server_list'):
                self.__ntpServerList = self.__arguments['server_list']
            if self.__arguments.has_key('timeout'):
                self.__timeout = self.__arguments['timeout']
        return


    """
    invoke: invoke ntp update method
    """
    def invoke(self):
        client   = None
        response = None
        try:
            client     = ntplib.NTPClient()
            response   = client.request(self.__ntpServerList[0], timeout = self.__timeout)
            updatetime = strftime("%Y-%m-%d %H:%M:%S %Z", localtime(int(response.dest_time)))
            subprocess.call(["date", "-s", updatetime])
        except NTPException,e:
            print e
        finally:
            if client is not None:
                del client
            if response is not None:
                del response
        return

if __name__ == "__main__":
    arguments = dict(server_list = ["1.cn.pool.ntp.org"], timeout = 5)
    ntpUpdate = NTPUpdate(arguments)
    ntpUpdate.invoke()
